package com.car.account.util.validatorUtil;

/**
 * 用于验证身份证号的格式正确性
 */
public class IDCardValidator {

    private static final String ID_CARD_PATTERN = "^\\d{17}(\\d|x|X)$";
    private static final int[] WEIGHTS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    private static final String CHECK_DIGITS = "10X98765432";

    public static boolean isValidIDCard(String idCard) {
        if (!idCard.matches(ID_CARD_PATTERN)) {
            return false;
        }

        String idCardWithoutCheck = idCard.substring(0, 17);
        char checkDigit = idCard.charAt(17);

        int sum = 0;
        for (int i = 0; i < idCardWithoutCheck.length(); i++) {
            int digit = Character.digit(idCardWithoutCheck.charAt(i), 10);
            sum += digit * WEIGHTS[i];
        }

        int modResult = sum % 11;
        char expectedCheckDigit = CHECK_DIGITS.charAt(modResult);

        return expectedCheckDigit == Character.toUpperCase(checkDigit);
    }

    public static void main(String[] args) {
        String idCard = "";
        System.out.println("ID Card is valid: " + isValidIDCard(idCard));
    }
}
